/*
 * iShopPlace Project.
 */
package ishopplace.view.bean;

import ishopplace.model.businessobject.*;
import ishopplace.model.exception.iShopPlaceException;
import ishopplace.view.util.FacesUtils;

import javax.faces.FacesException;

import org.springframework.beans.support.PagedListHolder;


/**
 * Category page bean for the view category page.
 * 
 * @author <a href="mailto:derek@derekshen.com">Derek Y. Shen</a>
 */
public class CategoryPageBean extends BasePaginationBean {
	private String categoryId;
	private String categoryName;
	
	public CategoryPageBean() {
		super();
		this.logger.debug("CategoryPageBean is created");
	}
	
	/**
	 * Initializes CategoryPageBean.
	 * 
	 * @see BaseBean#init()
	 */
	protected void init() {
		this.logger.debug("init() is invoked");
		this.logger.debug("categoryId = " + this.categoryId);
		this.logger.debug("page = " + this.getPage());
		
		Category category = null;
		if (this.categoryId != null) {
			category = FacesUtils.getApplicationBean().getCategory(this.categoryId);
			this.categoryName = category.getName();
			
			try {
				this.setPagedListHolder(new PagedListHolder(
					this.getServiceLocator().getCatalogService().getProductListByCategory(categoryId)));
			} catch (iShopPlaceException me) {
				String msg = "Could not retrieve product list for category id of " + this.categoryId;
				this.logger.error(msg, me);
				throw new FacesException(msg, me);
			}
			
			//put in the session bean
			FacesUtils.getSessionBean().setCurrentCategory(category);
			FacesUtils.getSessionBean().setCurrentProductList(this.pagedListHolder);
		}
		else {
			category = (Category)FacesUtils.getSessionBean().getCurrentCatetory();
			this.categoryName = category.getName();
			this.pagedListHolder = FacesUtils.getSessionBean().getCurrentProductList();
			
			if (category == null || this.pagedListHolder == null) {
				String msg = "Could not find category or product list in session";
				this.logger.error(msg);
				throw new FacesException(msg);
			}
			this.nagivate();
		}
		this.logger.debug("CategoryPageBean is initialized");
	}
	
	public void setCategoryId(String newCategoryId) {
		this.categoryId = newCategoryId;
	}
	
	public String getCategoryName() {
		return this.categoryName;
	}
}
